﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using SmartSpace;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Web;
using System.Web.UI.WebControls.WebParts;

namespace SmartSpace.WebApp
{
    public partial class _shell : System.Web.UI.Page
    {
        private Guid _applicationId;
        private Guid _navigationId;
        private string _viewsString;
        private string _pageName;
        private List<SmartSpace.Web.ViewInfo> _viewInfos = new List<SmartSpace.Web.ViewInfo>();

        protected override void OnPreInit(EventArgs e)
        {
            if (this.User == null || !this.User.Identity.IsAuthenticated
                || string.IsNullOrEmpty(this.User.Identity.Name))
            {
                Response.Redirect("./login.aspx");
            }
            else
            {
                try
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["_page"]))
                    {
                        _pageName = Request.QueryString["_page"];
                    }
                    string userName = Request.QueryString["_user"];

                    Logger.Debug(string.Format("visit page {0} ,app{1}", _pageName, SsSite.Current.HostUrl));

                    ICoreService service = ServiceLocator.Get<ICoreService>();
                    Site application = SsSite.Current;
                    User user = service.GetUser(User.Identity.Name);
                    SiteTemplate theme = service.GetSiteTemplate(application.TemplateId);
                    List<Shortcut> shortcuts = new List<Shortcut>();// service.GetUserShortcuts(application.Id, user.Id);
                    ListResult<Navigation> navigations = service.GetNavigations(application.Id);
                    List<Site> applications = service.GetSites();

                    System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(Server.MapPath("~/" + theme.Package));

                    SmartSpace.Web.ISiteTemplate themeInstance = (SmartSpace.Web.ISiteTemplate)assembly.CreateInstance(theme.Name);
                    SmartSpace.Web.IMainPanel mainPanel = themeInstance.GetMainPanel(this);

                    Control mycontrol = mainPanel.GetContentView();
                    this._panel.Controls.Add(mycontrol);

                    mainPanel.GetHeaderPanel().Initiate(shortcuts, applications, application, user);
                    mainPanel.GetNavigatePanel().Initiate(navigations.Data, shortcuts);

                    mainPanel.GetHeaderPanel().Logoff += new SmartSpace.Web.LogoffEventHandler(_shell_Logoff);
                    mainPanel.GetNavigatePanel().Navigating += _shell_Navigating;

                    VirtualPage page = service.GetPage(SsSite.Current.Id, _pageName);
                    mainPanel.GetWorkAreaPanel().SwitchView(this.LoadControl("~/_templates/_page/" + page.Template.Code + ".ascx"));

                }
                catch (Exception ex)
                {
                    Logger.Debug(string.Format("visit page error {0} ,{1}", Request.Url.OriginalString, ex.Message), ex);
                }

                base.OnPreInit(e);
            }


            //if (!string.IsNullOrEmpty(_viewsString))
            //{
            //    _viewsString = Encoding.UTF8.GetString(Convert.FromBase64String(_viewsString));
            //    System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(?<path>[^\\[\\]]*)\\[(?<arguments>[^\\[\\]]*)\\]");
            //    System.Text.RegularExpressions.MatchCollection matchs = regex.Matches(_viewsString);
            //    foreach (System.Text.RegularExpressions.Match match in matchs)
            //    {
            //        _viewInfos.Add(new SmartSpace.Web.ViewInfo
            //        {
            //            VirtualPath = match.Groups["path"].Value,
            //            Arguments = match.Groups["arguments"].Value
            //        });
            //    }
            //    string virtualPath = _viewInfos.Last().VirtualPath;
            //    string argumentString = _viewInfos.Last().Arguments;
            //    System.Collections.Specialized.NameValueCollection arguments = HttpUtility.ParseQueryString(argumentString.Replace(',', '&'));

            //    Navigation curNavigation = service.GetNavigation(_navigationId);
            //    Guid viewId = new Guid(curNavigation.Url.Replace("v:>>", string.Empty));
            //    ModuleView view = service.GetView(viewId);
            //    System.Reflection.Assembly moduleAssembly = System.Reflection.Assembly.LoadFile(Server.MapPath("~/" + view.Module.Package));

            //    SmartSpace.Web.AppModule moduleInstance = (SmartSpace.Web.AppModule)moduleAssembly.CreateInstance(view.Module.Name);
            //    SubView viewInstance = moduleInstance.GetView(this, virtualPath);
            //    mainPanel.GetWorkAreaPanel().SwitchView(viewInstance);
            //    viewInstance.OnShown(arguments);
            //    viewInstance.SwitchView += viewInstance_SwitchView;
            //}
        }

        void viewInstance_SwitchView(object sender, SwitchEventArgs e)
        {
            string originalViewString = string.Empty;

            foreach (var viewInfo in _viewInfos)
            {
                originalViewString += string.Format("{0}[{1}]/",
                    viewInfo.VirtualPath,
                    viewInfo.Arguments);
            }

            originalViewString += string.Format("{0}[{1}]/",
                e.VirtualPath,
                e.Arguments);

            originalViewString = Convert.ToBase64String(Encoding.UTF8.GetBytes(originalViewString));

            Response.Redirect(Request.Url.AbsolutePath + string.Format("?id={0}&nid={1}&__views={2}",
                _applicationId,
                _navigationId,
                originalViewString));
        }

        void _shell_Navigating(object sender, NavigatingEventArgs e)
        {
            Response.Redirect(Request.Url.AbsolutePath + string.Format("?id={0}&nid={1}", _applicationId, e.Navigation.Id.ToString()));
        }

        void _shell_Logoff(object sender, SmartSpace.Web.LogoffEventArgs e)
        {
            Response.Redirect("~/_logoff.aspx");
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            _ctlWebPartManager.DisplayMode = WebPartManager.BrowseDisplayMode;
            for (int index = 0; index < _ctlWebPartManager.Zones.Count; index++)
            {
                WebPartZoneBase zone = _ctlWebPartManager.Zones[index];
                zone.WebPartVerbRenderMode = WebPartVerbRenderMode.TitleBar;
                for (int iWebPart = 0; iWebPart < zone.WebParts.Count; iWebPart++)
                {
                    zone.WebParts[iWebPart].AllowClose = false;
                    zone.WebParts[iWebPart].AllowMinimize = false;
                }
            }
        }
    }
}